package com.sxt.service.impl;

import com.sxt.entity.IndexImg;
import com.sxt.mapper.IndexImgMapper;
import com.sxt.service.IndexImgService;

import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.Serializable;
import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * <p>
 * 主页轮播图 服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service
@Slf4j
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService {

	@Autowired
	private IndexImgMapper indexImgMapper ;
	
	/**
	 * 在写cacheable的key时,若是一个常量,必须使用'' 包起来,不然spring 会解析该长度,导致得到一个错误的值
	 * spring 会解析: 怎么解析的?
	 * #p0 p代表参数,0代表第几个参数  若是对象,则可以通过.属性的名称直接得到该值
	 * #变量名称 也可以取到值,对象要取到属性 #user.id
	 * spring el 表达式
	 * 
	 */
	private static final String INDEX_IMGS = "'all-index-imgs'";

	@Override
	public IPage<IndexImg> findByPage(Page<IndexImg> page, IndexImg indexImg) {
		log.info("查询{}，{}",page.getCurrent(),page.getSize());
		return indexImgMapper.selectPage(page, new LambdaQueryWrapper<IndexImg>().
				eq(indexImg.getStatus()!=null, IndexImg::getStatus, indexImg.getStatus()));
	}

	@Cacheable(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key="#id") // 单一的值
	public IndexImg getById(Serializable id) {
		return super.getById(id);
	}
	
	@CacheEvict(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key= INDEX_IMGS)
	public boolean save(IndexImg entity) {
		return super.save(entity);
	}
	
//	@CacheEvict(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key="#id") // 单一的值
//	@CacheEvict(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key= INDEX_IMGS ) // 给该方法添加缓存
	@Caching(
			evict = {
			@CacheEvict(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key="#id"),
			@CacheEvict(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key= INDEX_IMGS )
	})
	public boolean updateById(IndexImg entity) {
		return super.updateById(entity);
	}
	/**
	 * 完成首页数据的加载
	 */
	@Override
	/**
	 * cacheNames 缓存key的前缀,也被称为命名空间,能做缓存的隔离
	 * key: 缓存的标识
	 * 在redis 里面将会使用cacheNames+"::"+key的值 // 多个值
	 */
	@Cacheable(cacheNames = "com.sxt.service.impl.IndexImgServiceImpl",key= INDEX_IMGS ) // 给该方法添加缓存
	public List<IndexImg> loadIndexImgs() {
		return indexImgMapper.selectList(new LambdaQueryWrapper<IndexImg>().
				eq(IndexImg::getStatus, 1).orderByAsc(IndexImg::getSeq));
	}

}
